package sm.test;

import java.io.InputStream;
import java.sql.Blob;
import java.util.List;

import org.apache.mina.core.buffer.IoBuffer;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sm.codec.DBDictCodec;
import sm.codec.api.Codec;
import sm.dbdict.def.DBDict;
import sm.dbdict.def.SqlTables;

public class FullTableCheck2 {

	private static Logger logger = LoggerFactory
			.getLogger(FullTableCheck2.class);

	private static DBDict blobToDBDict(Codec codec, Blob blob) throws Exception {
		int length = (int) blob.length();
		byte[] bytes = new byte[length];
		InputStream is = blob.getBinaryStream();
		is.read(bytes);
		is.close();

		IoBuffer buffer = IoBuffer.wrap(bytes);
		DBDict des = (DBDict) codec.decode(buffer);
		return des;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			Codec codec = new DBDictCodec();
			SessionFactory sessionFactory = new Configuration().configure()
					.buildSessionFactory();
			Session session = sessionFactory.openSession();

			SQLQuery query = session
					.createSQLQuery("select NAME, DESCRIPTOR from DBDICTM1_BARCAP");
			List<Object[]> result = query.list();
			for (Object[] row : result) {
				String name = (String) row[0];
				Blob blob = (Blob) row[1];
				logger.info(name);
				DBDict dbdict = blobToDBDict(codec, blob);
				for (SqlTables sqlTables : dbdict.getSql_tables()) {
					String alias = sqlTables.getSql_table_alias();
					logger.info("alias: " + alias);
				}
			}

			session.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
